<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter, useRoute } from "vue-router";
import { message } from "@/utils/message";
// import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
// import { useUserStoreHook } from "@/store/modules/user";
// import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import {
  getLogin,
  Captch,
  sendCode,
  sendEmailCode,
  forgetphone,
  forgetemail
} from "@/api/user";
import { setToken } from "@/utils/auth";
import { addPathMatch, filterNoPermissionTree } from "@/router/utils";
import { usePermissionStoreHook } from "@/store/modules/permission";

import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
import { getSettings } from "@/api/setting";

const infos = ref({});

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title } = useNav();

const ruleForm = reactive({
  username: "",
  password: ""
});

const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // useUserStoreHook()
      //   .loginByUsername(ruleForm)
      //   .then(res => {
      //     if (res.success) {
      //       // 获取后端路由
      //       initRouter().then(() => {
      //         router.push(getTopMenu(true).path);
      //         message("登录成功", { type: "success" });
      //       });
      //     }
      //   });
      getLogin(ruleForm).then(res => {
        console.log("这是登陆数据", res.data);
        if (res.data.code == 200) {
          setToken({
            username: ruleForm.username,
            roles: [res.data.user_type == 1 ? "admin" : "common"],
            accessToken: res.data.token
          } as any);
          //  全部采取静态路由模式
          usePermissionStoreHook().handleWholeMenus([]);
          addPathMatch();
          localStorage.setItem("token", res.data.token);
          localStorage.setItem("user_type", res.data.user_type);
          localStorage.setItem("user_id", res.data.user_id);
          router.push("/");
          message("登录成功", { type: "success" });
        } else {
          message(res.data.data ? res.data.data : res.data.msg, {
            type: "error"
          });
          loading.value = false;
        }
      });
    } else {
      loading.value = false;
      return fields;
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}
// 忘记密码
const setforget = ref({
  phone: "",
  password: "",
  passwords: "",
  code: "",
  imgcode: "",
  email: "",
  setreg: 0,
  setcode: 0
});
const forgetbut = a => {
  if (a == 1) {
    (setforget.value.setreg = 1), (setforget.value.setcode = 1), getCaptch();
  } else if (a == 2) {
    (setforget.value.setreg = 0), (setforget.value.setcode = 0);
  }
};
// 图形验证码
const captchaSrc = ref("");
const hidecode = ref();
const getCaptch = async () => {
  let { data } = await Captch({});
  hidecode.value = data.data.hcode;
  captchaSrc.value = data.data.img;
};
const generateCaptcha = () => {
  getCaptch();
};
// 确认重置密码
const setreginfo = async setforget => {
  if (setforget.password == setforget.passwords && setforget.password) {
    if (setforget.setreg == 1) {
      const regex = /^1[3456789]\d{9}$/;
      if (regex.test(setforget.phone)) {
        phoneinfopass(setforget.phone, setforget.code, setforget.passwords);
      } else {
        message("不是一个有效的手机号码", { type: "error" });
      }
    } else if (setforget.setreg == 2) {
      const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (emailPattern.test(setforget.email)) {
        mailinfopass(setforget.email, setforget.passwords, setforget.code);
      } else {
        message("不是一个有效的邮箱", { type: "error" });
      }
    }
  } else if (setforget.password != setforget.passwords) {
    message("密码不一致", { type: "error" });
  } else if (setforget.code) {
    message("请输入验证码", { type: "error" });
  }
};
const clearSetforget = () => {
  const keys = Object.keys(setforget.value);
  for (const key of keys) {
    setforget.value[key] = "";
  }
};
// 手机&邮箱重置密码
const phoneinfopass = async (phone, code, password) => {
  let { data } = await forgetphone({
    phone,
    code,
    password
  });
  if (data.code == 200) {
    message(data.data, { type: "success" });
    clearSetforget();
  } else {
    message(data.data, { type: "error" });
  }
};
const mailinfopass = async (email, password, code) => {
  let { data } = await forgetemail({
    email,
    password,
    code
  });
  console.log(data);
  if (data.code == 200) {
    message(data.data, { type: "success" });
    clearSetforget();
  } else {
    message(data.data, { type: "error" });
  }
};
// 发送验证码
const ToSendCode = async id => {
  console.log(id);
  if (id == 1) {
    const regex = /^1[3456789]\d{9}$/;
    if (regex.test(setforget.value.phone)) {
      let { data } = await sendCode({
        send_to: setforget.value.phone,
        message_type: "send_code",
        code: setforget.value.imgcode,
        hcode: hidecode.value
      });
      if (data.code != 400) {
        message("发送成功", { type: "success" });
        timis();
      } else {
        message("图形验证码错误", { type: "error" });
      }
    } else {
      message("手机号码错误", { type: "error" });
    }
  } else if (id == 2) {
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (emailPattern.test(setforget.value.email)) {
      let { data } = await sendEmailCode({
        send_to: setforget.value.email,
        email_type: "send_code",
        code: setforget.value.imgcode,
        hcode: hidecode.value
      });
      if (data.code != 400) {
        message("发送成功", { type: "success" });
        timis();
      } else {
        message("图形验证码错误", { type: "error" });
      }
    } else {
      message("邮箱格式错误", { type: "error" });
    }
  }
};
// 计时器
const countdown = ref(60);
const sendbtn = ref(false);
const timis = () => {
  sendbtn.value = true;
  const timer = setInterval(() => {
    if (countdown.value <= 0) {
      clearInterval(timer);
      sendbtn.value = false;
      countdown.value = 60;
    } else {
      countdown.value -= 1;
    }
  }, 1000);
};
const route = useRoute();

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
  getSettings(["indexbg1", "address", "mainlogo"]).then(res => {
    console.log(res);
    infos.value = res.data.data;
  });
  console.log("11111", route.query);
  if (route.query.username && route.query.password) {
    ruleForm.username = route.query.username;
    ruleForm.password = route.query.password;
    getLogin(ruleForm).then(res => {
      console.log("这是登陆数据", res.data);
      if (res.data.code == 200) {
        setToken({
          username: ruleForm.username,
          roles: [res.data.user_type == 1 ? "admin" : "common"],
          accessToken: res.data.token
        } as any);
        //  全部采取静态路由模式
        usePermissionStoreHook().handleWholeMenus([]);
        addPathMatch();
        localStorage.setItem("token", res.data.token);
        localStorage.setItem("user_type", res.data.user_type);
        localStorage.setItem("user_id", res.data.user_id);
        if (route.query.container_id) {
          if (res.data.user_type == 1) {
            router.push({
              path: "/servers/containers",
              query: {
                container_id: route.query.container_id
              }
            });
          } else {
            router.push({
              path: "/self/container",
              query: {
                container_id: route.query.container_id
              }
            });
          }
        } else if (route.query.instance_id) {
          console.log("instance_id", route.query.instance_id);
          if (res.data.user_type == 1) {
            router.push({
              path: "/servers/virtualInfo",
              query: {
                container_id: route.query.instance_id
              }
            });
          } else {
            router.push({
              path: "/self/vmContainer",
              query: {
                container_id: route.query.instance_id
              }
            });
          }
        } else {
          router.push("/");
        }
        message("登录成功", { type: "success" });
      } else {
        message(res.data.data ? res.data.data : res.data.msg, {
          type: "error"
        });
        loading.value = false;
      }
    });
  }
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <img :src="infos.indexbg1" class="wave" />
    <div class="flex-c absolute right-5 top-3 header">
      <img style="width: 200px; margin-left: 25px" :src="infos.mainlogo" @click="router.push('/home/home')" />
      <!-- 主题 -->
      <el-switch v-model="dataTheme" inline-prompt :active-icon="dayIcon" :inactive-icon="darkIcon"
        @change="dataThemeChange" />
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <!-- <avatar class="avatar" /> -->
          <img class="logoimg" :src="infos.mainlogo" />
          <Motion>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion>
          <div v-if="setforget.setcode != 0" class="register-mode-selector">
            <el-radio-group v-model="setforget.setreg" class="change-mode">
              <el-radio-button label="1">手机号找回</el-radio-button>
              <el-radio-button label="2">邮箱找回</el-radio-button>
            </el-radio-group>
          </div>
          <el-form ref="ruleFormRef" :model="ruleForm" size="large">
            <!-- 登录页 -->
            <Motion v-if="setforget.setcode == 0" :delay="100">
              <el-form-item :rules="[
                {
                  required: true,
                  message: '请输入邮箱/手机号/用户名',
                  trigger: 'blur'
                }
              ]" prop="username">
                <el-input v-model="ruleForm.username" clearable placeholder="邮箱/手机号/用户名"
                  :prefix-icon="useRenderIcon(User)" />
              </el-form-item>
            </Motion>
            <Motion v-if="setforget.setcode == 0" :delay="150">
              <el-form-item prop="password">
                <el-input v-model="ruleForm.password" clearable show-password placeholder="密码"
                  :prefix-icon="useRenderIcon(Lock)" />
              </el-form-item>
            </Motion>
            <!-- 忘记密码页 -->
            <Motion v-if="setforget.setreg == 1" :delay="100">
              <el-form-item prop=" phone">
                <el-input v-model="setforget.phone" clearable placeholder="手机" />
              </el-form-item>
            </Motion>
            <Motion v-if="setforget.setreg == 2" :delay="100">
              <el-form-item prop="email">
                <el-input v-model="setforget.email" clearable placeholder="邮箱" />
              </el-form-item>
            </Motion>
            <Motion v-if="setforget.setcode != 0" :delay="100">
              <el-form-item prop="imgcode">
                <div class="captcha-input-container">
                  <el-input v-model="setforget.imgcode" clearable placeholder="图形验证码" />
                  <img width="100" :src="captchaSrc" alt="图形验证码" @click="generateCaptcha()" />
                </div>
              </el-form-item>
            </Motion>
            <Motion v-if="setforget.setcode != 0" :delay="100">
              <el-form-item prop="code">
                <div class="captcha-input-container">
                  <el-input v-model="setforget.code" clearable placeholder="请输入验证码" />
                  <el-button type="primary" width="100" :disabled="sendbtn" @click="ToSendCode(setforget.setreg)">
                    {{
                      sendbtn ? `重新发送(${countdown}s)` : "发送验证码"
                    }}</el-button>
                </div>
              </el-form-item>
            </Motion>
            <Motion v-if="setforget.setcode != 0" :delay="150">
              <el-form-item prop="password">
                <el-input v-model="setforget.password" clearable show-password placeholder="输入密码" />
              </el-form-item>
            </Motion>
            <Motion v-if="setforget.setcode != 0" :delay="150">
              <el-form-item prop="Passwords">
                <el-input v-model="setforget.passwords" clearable show-password placeholder="确认密码" />
              </el-form-item>
            </Motion>

            <div style="display: flex; justify-content: space-between">
              <div class="regibutton">
                <div class="regbut" @click="router.push('/register')">
                  注册账户
                </div>
                <div v-if="setforget.setcode == 0" @click="forgetbut(1)">
                  忘记密码
                </div>
                <div v-if="setforget.setcode != 0" @click="forgetbut(2)">
                  去登录
                </div>
              </div>
              <div class="regibutton">
                <a href="/serviceterm.html">服务条款</a>
                <a href="/privacy.html">隐私政策</a>
              </div>
            </div>
            <Motion v-if="setforget.setcode == 0" :delay="250">
              <el-button class="w-full mt-4" size="default" type="primary" :loading="loading"
                @click="onLogin(ruleFormRef)">
                登录
              </el-button>
            </Motion>
            <Motion v-if="setforget.setcode != 0" :delay="250">
              <el-button class="w-full mt-4" size="default" type="primary" :loading="loading"
                @click="setreginfo(setforget)">
                确认密码
              </el-button>
            </Motion>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.change-mode {
  margin-bottom: 20px;
}

.captcha-input-container {
  display: flex;
  align-items: center;
}

.regibutton {
  font-size: 12px;
  color: #409eff;
  text-align: left;
  display: flex;

  a {
    margin-left: 8px;
  }

  .regbut {
    margin-right: 10px;
  }

  span {
    padding-left: 10px;
  }
}

.header {
  display: felx;
  justify-content: space-between;
  width: 100%;
}

@media screen and (max-width: 480px) {
  .logoimg {
    display: none;
  }
}
</style>
